/*********************************************************************
 * File Name: beep.c
 * Summary: GPIO subsystem based beep driver with device tree support
 * Description: 
 * This file implements a character device driver for beep control
 * using GPIO subsystem and device tree configuration.
 *
 * Key Features:
 * - Device tree based GPIO configuration
 * - GPIO subsystem API usage
 * - Character device registration with cdev structure
 * - Device class and device node creation
 * - User space to kernel space data transfer
 * - Modern Linux kernel driver architecture
 *
 * Modification History:
 * Version    Author      Date        Changes
 *--------------------------------------------------
 * 1.00.00    yushuang    2025-09-13  Initial release
 *--------------------------------------------------
 ********************************************************************/

#include <linux/types.h>   /**< ssize_t, size_t, loff_t, __user */
#include <linux/kernel.h>  /**< printk, memcpy, error codes */
#include <linux/delay.h>   /**< udelay, mdelay */
#include <linux/ide.h>     /**< IDE related definitions */
#include <linux/init.h>    /**< __init, __exit, module_init, module_exit */
#include <linux/module.h>  /**< THIS_MODULE, MODULE_LICENSE, MODULE_AUTHOR */
#include <linux/errno.h>   /**< Error codes */
#include <linux/gpio.h>    /**< GPIO subsystem API */
#include <linux/cdev.h>    /**< Character device structure */
#include <linux/device.h>  /**< Device class and device creation */
#include <linux/of.h>      /**< Device tree support */
#include <linux/of_address.h> /**< Device tree address functions */
#include <linux/of_gpio.h> /**< Device tree GPIO functions */
#include <asm/mach/map.h>  /**< Memory mapping functions */
#include <asm/uaccess.h>  /**< User space access functions */
#include <asm/io.h>       /**< I/O access functions */

#define BEEP_CNT      1           /**< Number of device instances */
#define BEEP_NAME     "beep"      /**< Device name */
#define BEEPOFF       0           /**< Beep off state */
#define BEEPON        1           /**< Beep on state */

/* Beep Electrical Characteristics:
 * - Beep is connected between GPIO and VCC (active high)
 * - GPIO = 1 (high) -> Beep ON
 * - GPIO = 0 (low) -> Beep OFF
 */

/* Device structure */
struct beep_dev
{
    dev_t devid;            /* Device number */
    struct cdev cdev;       /* Character device */
    struct class *class;    /* Device class */
    struct device *device;  /* Device instance */
    int major;              /* Major number */
    int minor;              /* Minor number */
    struct device_node *nd; /* Device tree node */
    int beep_gpio;          /* GPIO number for beep control */
};

struct beep_dev beep = {0};     /* Beep device - initialize to zero */

/**
 * @brief Open device function
 * @param inode Inode structure passed to driver
 * @param filp File structure, contains private_data member variable
 *              which is usually set to point to device structure during open
 * @return 0 on success, negative value on failure
 */
static int beep_open(struct inode *inode, struct file *filp)
{
    filp->private_data = &beep; /* Set device pointer */
    return 0;
}

/**
 * @brief Read data from device
 * @param filp Device file to read from (file descriptor)
 * @param buf Buffer to return data to user space
 * @param cnt Number of bytes to read
 * @param offt Offset relative to file start address
 * @return Number of bytes read, negative value on failure
 */
static ssize_t beep_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
    int retvalue;
    unsigned char beepstat;
    struct beep_dev *dev = filp->private_data;

    /* Limit read size to prevent buffer overflow */
    if (cnt > 1)
    {
        printk("Read size too large, max 1 byte\n");
        return -EINVAL;
    }

    /* Get current beep state from GPIO */
    beepstat = gpio_get_value(dev->beep_gpio);
    /* Convert GPIO value to beep state: GPIO=1 means Beep ON, GPIO=0 means Beep OFF */
    beepstat = (beepstat == 1) ? BEEPON : BEEPOFF;

    retvalue = copy_to_user(buf, &beepstat, cnt);  /* Copy to user space */
    if (retvalue > 0)  /* copy_to_user returns number of bytes NOT copied */
    {
        printk("kernel read failed!\r\n");
        return -EFAULT;
    }

    return cnt;  /* Return number of bytes read */
}

/**
 * @brief Write data to device
 * @param filp Device file representing opened file descriptor
 * @param buf Data to write to device
 * @param cnt Number of bytes to write
 * @param offt Offset relative to file start address
 * @return Number of bytes written, negative value on failure
 */
static ssize_t beep_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    int retvalue;
    unsigned char databuf[1];
    unsigned char beepstat;
    struct beep_dev *dev = filp->private_data;

    /* Limit write size to prevent buffer overflow */
    if (cnt > 1)
    {
        printk("Write size too large, max 1 byte\n");
        return -EINVAL;
    }

    retvalue = copy_from_user(databuf, buf, cnt);  /* Copy from user space */
    if (retvalue > 0)  /* copy_from_user returns number of bytes NOT copied */
    {
        printk("kernel write failed!\r\n");
        return -EFAULT;
    }

    beepstat = databuf[0];       /* Get beep control value */

    if (beepstat == BEEPON)
    {
        gpio_set_value(dev->beep_gpio, 0);  /* Set GPIO high to turn on beep */
    }
    else if (beepstat == BEEPOFF)
    {
        gpio_set_value(dev->beep_gpio, 1);  /* Set GPIO low to turn off beep */
    }
    return cnt;  /* Return number of bytes written */
}

/**
 * @brief Close/release device function
 * @param inode Inode structure
 * @param filp Device file to close (file descriptor)
 * @return 0 on success, negative value on failure
 */
static int beep_release(struct inode *inode, struct file *filp)
{
    return 0;
}

/* File operations */
static struct file_operations beep_fops = {
    .owner = THIS_MODULE,
    .open = beep_open,
    .read = beep_read,
    .write = beep_write,
    .release = beep_release,
};

/**
 * @brief Driver initialization function
 * @param None
 * @return None
 */
static int __init beep_init(void)
{
    int ret = 0;

    /* Initialize beep hardware using device tree */
    /* 1. Find device tree node: beep */
    beep.nd = of_find_node_by_path("/beep");
    if (beep.nd == NULL)
    {
        printk("beep node not found!\r\n");
        return -EINVAL;
    }
    else
    {
        printk("beep node found!\r\n");
    }

    /* 2. Get GPIO property from device tree, get beep GPIO number */
    beep.beep_gpio = of_get_named_gpio(beep.nd, "beep-gpio", 0);
    if (beep.beep_gpio < 0)
    {
        printk("can't get beep-gpio\r\n");
        return -EINVAL;
    }
    printk("beep-gpio num = %d\r\n", beep.beep_gpio);

    /* 3. Request GPIO resource - temporarily disabled for testing */
    /*
    ret = gpio_request(beep.beep_gpio, "beep-gpio");
    if (ret < 0)
    {
        printk("can't request beep-gpio!\r\n");
        return -EINVAL;
    }
    */

    /* 4. Set GPIO as output with high level, beep off by default */
    ret = gpio_direction_output(beep.beep_gpio, 1);
    if (ret < 0)
    {
        printk("can't set gpio!\r\n");
        /* gpio_free(beep.beep_gpio); - temporarily disabled */
        return -EINVAL;
    }

    /* Register character device driver */
    /* 5. Create device number */
    if (beep.major)
    {
        beep.devid = MKDEV(beep.major, 0);
        register_chrdev_region(beep.devid, BEEP_CNT, BEEP_NAME);
    }
    else
    {
        alloc_chrdev_region(&beep.devid, 0, BEEP_CNT, BEEP_NAME);  /* Allocate device number */
        beep.major = MAJOR(beep.devid);     /* Get allocated major device number */
        beep.minor = MINOR(beep.devid);     /* Get allocated minor device number */
    }
    printk("beep major=%d,minor=%d\r\n", beep.major, beep.minor);

    /* 6. Initialize character device structure */
    beep.cdev.owner = THIS_MODULE;
    cdev_init(&beep.cdev, &beep_fops);

    /* 7. Add character device to kernel */
    ret = cdev_add(&beep.cdev, beep.devid, BEEP_CNT);
    if (ret < 0)
    {
        printk("cdev_add failed!\r\n");
        unregister_chrdev_region(beep.devid, BEEP_CNT);
        /* gpio_free(beep.beep_gpio); - temporarily disabled */
        return ret;
    }

    /* 8. Create device class */
    beep.class = class_create(THIS_MODULE, BEEP_NAME);
    if (IS_ERR(beep.class))
    {
        printk("class_create failed!\r\n");
        cdev_del(&beep.cdev);
        unregister_chrdev_region(beep.devid, BEEP_CNT);
        /* gpio_free(beep.beep_gpio); - temporarily disabled */
        return PTR_ERR(beep.class);
    }

    /* 9. Create device node in /dev/ */
    beep.device = device_create(beep.class, NULL, beep.devid, NULL, BEEP_NAME);
    if (IS_ERR(beep.device))
    {
        printk("device_create failed!\r\n");
        class_destroy(beep.class);
        cdev_del(&beep.cdev);
        unregister_chrdev_region(beep.devid, BEEP_CNT);
        /* gpio_free(beep.beep_gpio); - temporarily disabled */
        return PTR_ERR(beep.device);
    }
    return 0;
}

/**
 * @brief Driver exit function
 * @param None
 * @return None
 */
static void __exit beep_exit(void)
{
    /* Free GPIO resource - temporarily disabled for testing */
    /*
    gpio_free(beep.beep_gpio);
    */

    /* Unregister character device driver */
    /* Destroy device node first, then remove cdev */
    if (beep.device)
    {
        device_destroy(beep.class, beep.devid);
    }

    if (beep.class)
    {
        class_destroy(beep.class);
    }

    cdev_del(&beep.cdev);                     /* Remove cdev from kernel */
    unregister_chrdev_region(beep.devid, BEEP_CNT);  /* Free device number */
}

module_init(beep_init);
module_exit(beep_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("yushuang");